import 'package:casdon/core/utils/string_externtion.dart';
import 'package:casdon/modules/recipe/data/model/recipe_placeholder_data.dart';
import 'package:json_annotation/json_annotation.dart';

part 'recipe_cloud_list_api.g.dart';

// 请求参数模型
@JsonSerializable()
class RequestRecipeCloudListApi {
  final List<String> name;
  final String pid;
  final int isLocal = 0;
  final int pageNum;
  final int pageSize;

  factory RequestRecipeCloudListApi.fromJson(Map<String, dynamic> json) =>
      _$RequestRecipeCloudListApiFromJson(json);

  RequestRecipeCloudListApi({
    required this.name,
    required this.pid,
    required this.pageNum,
    required this.pageSize,
  });

  Map<String, dynamic> toJson() => _$RequestRecipeCloudListApiToJson(this);
}

// 响应模型
@JsonSerializable()
class ResponseRecipeCloudListApi {
  final int total;
  final List<RecipeCloud>? rows;

  ResponseRecipeCloudListApi(this.total, this.rows);

  factory ResponseRecipeCloudListApi.fromJson(Map<String, dynamic> json) =>
      _$ResponseRecipeCloudListApiFromJson(json);

  Map<String, dynamic> toJson() => _$ResponseRecipeCloudListApiToJson(this);
}

// 菜谱内容模型
@JsonSerializable()
class RecipeCloud {
  @JsonKey(name: 'imageUrls', fromJson: _getImageUrl, toJson: _imageUrlToJson)
  final String? imageUrl; // 封面图

  final String? name; // 名称
  final int isControl;
  final String? id; // ID

  final String? view; // 浏览数

  RecipeCloud({
    this.imageUrl,
    this.name,
    required this.isControl,
    required this.id,
    required this.view,
  });

  factory RecipeCloud.fromJson(Map<String, dynamic> json) =>
      _$RecipeCloudFromJson(json);

  Map<String, dynamic> toJson() => _$RecipeCloudToJson(this);

  // 自定义转换函数
  static String? _getImageUrl(dynamic value) {
    if (value is String && value.isNotEmpty) {
      return value.split(",").first;
    }
    return recipePlaceHolderImgUrl;
  }

  // 反向序列化方法
  static dynamic _imageUrlToJson(String? url) => url;
}
